package drp.snowbell.lang;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import drp.snowbell.cfg.Config;
import drp.snowbell.cfg.Location;
import drp.snowbell.exception.CatchException;


/**
 * 语言包管理.
 * 
 * @author woj
 * 
 */
public class Culture {

	private static Map<String, Map<String, String>> langMap = new HashMap<String, Map<String, String>>();
	private static Object lock = new Object();

	public static String get(ILanguage lang) {
		String ret = null;
		if (lang != null) {
			String moduleName = lang.getModuleName();
			Enum<?> langEnum = (Enum<?>) lang;
			String lable = langEnum.name();
			ret = get(moduleName, lable);
		}
		return ret;
	}

	public static String get(String moduleName, String label) {
		String ret = null;
		Map<String, String> map = null;
		if (moduleName == null) {
			moduleName = Config.CORE_MODULE_NAME;
		}
		if (langMap.containsKey(moduleName)) {
			map = langMap.get(moduleName);
		} else {
			map = getLanguageMap(moduleName);
			synchronized (lock) {
				langMap.put(moduleName, map);// 添加缓存
			}
		}
		ret = map.get(label);
		if (ret == null) {
			ret = label;// 如果找不到返回label
		}
		return ret;
	}

	/**
	 * 获取系统语言
	 * 
	 * @param lable
	 * @return
	 */
	public static String get(String label) {
		return get(null, label);
	}

	/**
	 * 获取语言列表
	 * 
	 * @param beanName
	 * @return
	 */
	private static Map<String, String> getLanguageMap(String moduleName) {
		// 获取语言包地址
		String path = Location.getModuleLangPath(moduleName);

		Properties prop = new Properties();

		Map<String, String> ret = new HashMap<String, String>();
		try {
			prop.load(new FileInputStream(path));
			Enumeration<?> keys = prop.keys();
			while (keys.hasMoreElements()) {
				String key = keys.nextElement().toString();
				ret.put(key, prop.getProperty(key));
			}

		} catch (IOException e) {
			CatchException.take(Culture.class, e);
		}

		return ret;
	}
}
